<template>
    <div>
        <div class="mt14" v-if="importTemplate.widgetList.length" v-loading="formloading" style="position: relative;">
         <div class="button fixnew btn-shadow">
            <el-button size="mini" type="primary" :loading="loading" @click="saveFn" :disabled="oneboom.bomm_ap_flag">保存</el-button>
            <el-button size="mini" icon="el-icon-finished"  type="danger" @click="piheData" :disabled="oneboom.bomm_ap_flag">批核</el-button>
            <el-button size="mini" icon="el-icon-edit-outline" type="info" @click="fanpiheData" :disabled="!oneboom.bomm_ap_flag">反批核</el-button>
         </div>
         <!-- formDataAllNew.length > 0 -->
          <div class="" style="margin-top:40px;" v-if="isSubmitFlag">
              <formtable ref="wulidangan" :disableds="disableds" :flagStatu="flagStatu" :dangqianIndex="dangqianIndex" :parentData="parentData" :treeData="treeData" :pagestatus="pagestatus" :keyName="keyName" :testFormData="testFormData" :id="id" :typeid="wltypeid" :isSubmit="isSubmit"  :formDataAll="formDataAllNew" @handlerisSubmitVal="handlerisSubmitVal" @getFormSumbit="getFormSumbit"></formtable>
          </div>
        </div>
        <div v-else>
          <default-page :index="16" :min-height="420" />
        </div>
    </div>
  </template>
  <script>
  import VFormRender from '@/components/form-render/index'
  import defaultPage from '@/components/common/defaultPage'
  import { crudModuleCreateApi, crudModuleSaveDataApi, crudModuleUpdateApi, crudFangkeSaveApi, crudFangkeuserCreateApi, crudModuleBatchDelApi,
    crudForminsertDataAllApi, putUpdateFieldApi 
   } from '@/api/develop'
  import { FacialVerificationApi } from '@/api/enterprise'
  import ApiUrl from '@/api/apiUrls' // dengshunbo 2024-12-27新增
  import formtable from './formtable.vue'
  export default {
    components: { VFormRender, defaultPage, formtable },
    props: {
      keyName: {
        type: String,
        default: ''
      },
      crud: {
        type: Object,
        default: () => {}
      },
      pagestatus: {
         type: Number,
         default: 1
      },
      treeData: {
         type: [Array, Object],
         default: () => []
      },
      childGyData: {
         type: [Object, Array],
         default: ()=>{
            return {}
         }
      },
      dangqianIndex: {
        type: Number,
         default: 1
      },
      formDataAll: {
         type: [Array],
         default: ()=>{
            return []
         }
      },
      oneboom: {
        type: [Object],
        default: ()=>{
           return {};
        }
      },
      disableds: {
         type: Boolean,
         default: false
      }
      
    
     
    },
    data() {
      return {
        isSubmit: 0,
        importTemplate: {
          formConfig: {},
          widgetList: []
        },
        title: '新增',
        id: 0, // 当前列表的id值
        designer: {},
        testFormData: {},
        loading: false,
        testOptionData: {
          select62173: [
            
          ],
          select001: [
            
          ]
        },
        formloading: false,
        drawerData:{},
        indexflag: 1,
        wltypeid: 0,
       
        formdatasubmit:{},
        isFlage: false,
        flagStatu: 0,
       
        formDataAllNew: [],
        parentData: {},
        wulidanganFlag: false,
        isSubmitFlag: false,
        userinfo: {},
      }
    },
    computed: {
      designerDsv() {
        return this.globalDsv
      }
    },
    mounted() {
      let useradmin = window.localStorage.getItem('userInfo') || '{}'
      if(useradmin){
         this.userinfo = JSON.parse(useradmin);
      }

    }, 
    beforeDestroy(){
         console.log("关闭了")
    },
    methods: {
        // 组件关闭调用方法，清除组件缓存数据
        resethandler(){
          if(this.formDataAllNew.length > 0){
                this.formDataAllNew.map((item)=>{
                  item.allTableData = {};
                  item.oldData = [];
                  item.tableData = [];
              })
              this.formDataAllNew = []
          }
          this.isSubmitFlag = false
          this.$refs.wulidangan.resetchildhandler()
        },
        // 上组件传过来的数据
        async openBox(id, data, index=0, item='') {
            this.formDataAllNew = this.formDataAll;
            this.parentData = data; // 当前左侧选中数据
            this.formDataAllNew[0].allgyData = this.childGyData.gydata;
            this.formDataAllNew[0].gy = this.childGyData.gy; // 物料清单数据
            this.id = id || 0; // 当前左侧选中数据id
            if(index==0){ // 有子级children数据
                if(item && item.length > 0){  //  物料清单数据
                    this.formDataAllNew[0].tableData = item;
                    this.formDataAllNew[0].allTableData = {}
                }else{
                    this.formDataAllNew[0].tableData = []
                    this.formDataAllNew[0].allTableData = {}
                }
                let obj = {}
                if (this.crud) {
                    obj.crud_id = this.crud.crud_id
                    obj.crud_value = this.crud.crud_value
                } else {
                    obj = {}
                }
                obj.id = id
                const res = await crudModuleCreateApi(this.keyName, obj)
                if (res.data.form_info && res.data.form_info.global_options) {
                    this.$set(this.importTemplate, 'formConfig', res.data.form_info.global_options)
                }
                this.$set(this.importTemplate, 'widgetList', res.data.form_info.options)
            }
            this.isSubmitFlag = true;
            this.isSubmit = 1;
        },
        hasDuplicateIds(arr1, arr2){
          if (arr1.length === 0 || arr2.length === 0) return false;
          const idSet = new Set(arr1.map(item => item.id));
          return arr2.some(item => idSet.has(item.id));
        },
        handlerisSubmitVal(index=0){
          this.isSubmit = 0;
        },
        getFormSumbit(index){

        },
       
        // 物料清单关联表数据进行处理保存
        async handlerWLQDSaveTabelFilter(saveid){
            let formTabledata = this.$refs.wulidangan.formtable;
            console.log("formTabledata", formTabledata)
            let isupnum  = 1
            for(let i=0;i<formTabledata.length;i++){
                let deleteData = formTabledata[i].deleteData;
                if(deleteData.length > 0){ // 删除
                  await crudModuleBatchDelApi(formTabledata[i].value, {ids: deleteData}, true);
                  isupnum = 2
                }
                let wlqdList = [],wlqdListold = [];
                let alltabData = formTabledata[i].allTableData;
                let alltabDataold = formTabledata[i].oldData;
                for(let a in  alltabData){
                    for(let b=0; b < alltabData[a].length;b++){
                      wlqdList.push(alltabData[a][b])
                    }
                }
                for(let a in  alltabDataold){
                    for(let b=0; b <alltabDataold[a].length;b++){
                      wlqdListold.push(alltabDataold[a][b])
                    }
                }
                let formlinedatas = this.getArrayChanges(wlqdList, wlqdListold);
                if(formlinedatas.added && formlinedatas.added.length > 0){ // 要添加的数据
                   await this.handerAddSaveForm(formTabledata[i], formlinedatas.added, this.userinfo.id)
                   isupnum = 3;
                }
                if(formlinedatas.updated && formlinedatas.updated.length > 0){ // 要更新的数据
                  await this.handlerUpdateSaveForm(formTabledata[i], formlinedatas.updated)
                  isupnum = 4
                }             
            }
            if(isupnum == 4){
               this.$message.success("更新成功")
            }else if(isupnum == 3){
               this.$message.success("新增成功")
            }else if(isupnum == 2){
               this.$message.success("删除成功")
            }
            let listtime = setTimeout(()=>{
              clearTimeout(listtime)
              this.$emit('getList', 0, 2)
            }, 200)
            
        },
        // 新增数据处理方法
        async handerAddSaveForm(parentData, fdata, uid){
            let addData = []
            if(parentData.value == 'wuliaoqingdanbiao') { //物料清单
              for(let i=0;i < fdata.length;i++){
                let formdata2 = {};
                formdata2.wuliaobianmaid = fdata[i].wuliaobianmaid; // 物料编码id(物料档案表)
                formdata2.fuwuliaobianmaid = fdata[i].fuwuliaobianmaid; // 父物料编码id(物料档案表)
                formdata2.shiyongbumen = fdata[i].shiyongbumen; // 使用部门(工序设置表数据)
                formdata2.sunhaoleixing = fdata[i].sunhaoleixing; // 损耗类型(损耗类型字典)
                formdata2.user_id = uid; // 添加用户id
                formdata2.beizhu = fdata[i].beizhu;// 备注
                formdata2.wuliaodanganid = fdata[i].wuliaobianmaid; // 物料档案id(物料编码id)
                formdata2.sunhaodaima = fdata[i].sunhaodaima; // 损耗代码
                formdata2.jishu =  fdata[i].jishu; // 基数
                formdata2.sunhao = fdata[i].sunhao; // 损耗
                formdata2.tiaoji = fdata[i].tiaoji; // 调机
                formdata2.sunhaodaima = fdata[i].sunhaodaima; // 损耗代码
                formdata2.dahuodingliao = fdata[i].dahuodingliao;// 大货订料
                formdata2.dahuoquedingriqi = fdata[i].dahuoquedingriqi || null; // 大货订料日期
                formdata2.yangbandingliao = fdata[i].yangbandingliao; // 样板订料
                formdata2.yangbanquedingriqi = fdata[i].yangbanquedingriqi || null; // 样板订料日期
                formdata2.yongliang = fdata[i].yongliang;
                addData.push(formdata2)
              }
            }else if(parentData.value == 'gongyi'){ //工艺
              for(let j=0;j < fdata.length;j++){
                let formdata2 = {
                    user_id: uid, // 添加用户id
                    baogong: fdata[j].baogong, // 报工
                    beizhu: fdata[j].beizhu, // 备注
                    bengongxuid: fdata[j].bengongxuid, // 本工序
                    daogongxuid: fdata[j].daogongxuid, // 到工序
                    daopeijianleixing: '', // 到配件类型
                    gongjia: fdata[j].gongjia, // 工价
                    gongyinandu: fdata[j].gongyinandu, // 工艺难度
                    laiyuan: fdata[j].laiyuan, // 来源
                    peijianleixing: '', // 配件类型
                    peijianxuhao: fdata[j].peijianxuhao, // 配件序号
                    shengchanzhouqi: fdata[j].shengchanzhouqi, // 生产周期
                    wuliaodangan: fdata[j].wuliaodangan
                }
                if(fdata[j].bengongxuid){ //本工序
                    let imdata = parentData.datadictList.bengongxuid;
                    for(let i=0;i<imdata.length;i++){
                      if(fdata[j].bengongxuid == imdata[i].gongxudaima || fdata[j].bengongxuid == imdata[i].zhongwenmiaoshu || fdata[j].bengongxuid == imdata[i].id ){
                          formdata2.bengongxuid = imdata[i].id
                          break;
                      }
                    }
                }
                if(fdata[j].daogongxuid){ // 到工序
                    let imdata = parentData.datadictList.bengongxuid;
                    for(let i=0;i<imdata.length;i++){
                      if(fdata[j].daogongxuid == imdata[i].gongxudaima || fdata[j].daogongxuid == imdata[i].zhongwenmiaoshu || fdata[j].daogongxuid == imdata[i].id ){
                          formdata2.daogongxuid =  imdata[i].id
                          break;
                      }
                    }
                }
                if(fdata[j].peijianleixing){ // 配件类型
                    let imdata = parentData.datadictList.peijianleixing;
                    for(let i=0;i<imdata.length;i++){
                      if(fdata[j].peijianleixing == imdata[i].value || fdata[j].peijianleixing == imdata[i].name ){
                          formdata2.peijianleixing = imdata[i].value;
                          break;
                      }
                    }
                }
                if(fdata[j].daopeijianleixing){ // 到配件类型
                    let imdata = parentData.datadictList.peijianleixing;
                    for(let i=0;i<imdata.length;i++){
                      if(fdata[j].daopeijianleixing == imdata[i].value || fdata[j].daopeijianleixing == imdata[i].name ){
                          formdata2.daopeijianleixing = imdata[i].value;
                          break;
                      }
                    }
                }
                addData.push(formdata2)
              }
                  
            }
            console.log("addData", addData)
            let objss = { table: parentData.value, data: encodeURI(JSON.stringify(addData))  }
            await crudForminsertDataAllApi(objss)
                 
           
        },
        // 更新数据处理方法 
        async handlerUpdateSaveForm(parentobj, fdata){
          let danganid = this.parentData.wuliaobianmaid ? this.parentData.wuliaobianmaid: this.parentData.id;
           for(let j=0;j<fdata.length;j++){
              let newitem = fdata[j].new;
              let formdata2 = {}
              if(parentobj.value=='wuliaoqingdanbiao'){
                  formdata2.beizhu = newitem.beizhu || ''
                  formdata2.dahuodingliao = newitem.dahuodingliao;
                  formdata2.dahuoquedingriqi = this.hadnlerriqiFilter(newitem.dahuoquedingriqi);
                  formdata2.fuwuliaobianmaid = {id: newitem.fuwuliaobianmaid, name: ''}
                  formdata2.wuliaobianmaid = {id: newitem.wuliaobianmaid, name: newitem.item_sn}
                  formdata2.jishu = newitem.jishu
                  formdata2.sunhao = newitem.sunhao
                  formdata2.sunhaodaima = newitem.sunhaodaima
                  formdata2.shiyongbumen = ''

                  if(newitem.sunhaoleixing){ // 损耗类型
                    let imdata = parentobj.datadictList.sunhaoleixing;
                    for(let i=0;i<imdata.length;i++){
                      if(newitem.sunhaoleixing == imdata[i].value || newitem.sunhaoleixing == imdata[i].name ){
                          formdata2.sunhaoleixing = [imdata[i].value];
                      }
                    }
                  }
                  if(newitem.shiyongbumen){
                    let imdata = parentobj.datadictList.shiyongbumen;
                    for(let i=0;i<imdata.length;i++){
                      if(newitem.shiyongbumen == imdata[i].id || newitem.shiyongbumen == imdata[i].gongxudaima || newitem.shiyongbumen == imdata[i].zhongwenmiaoshu ){
                          formdata2.shiyongbumen = {id: imdata[i].id, name: imdata[i].gongxudaima}
                          break;
                      }
                    }
                  }
                  formdata2.wuliaodanganid = newitem.wuliaodanganid?newitem.wuliaodanganid:newitem.wuliaobianmaid
                  formdata2.yangbandingliao = newitem.yangbandingliao
                  formdata2.yangbanquedingriqi = this.hadnlerriqiFilter(newitem.yangbanquedingriqi);
                  formdata2.yongliang = newitem.yongliang
              }else if(parentobj.value == 'gongyi'){
                  formdata2 = JSON.parse(JSON.stringify(newitem));
                  if(newitem.wuliaodangan){ // 物料档案
                      formdata2.wuliaodangan = {id: newitem.wuliaodanganid, name: newitem.wuliaodangan}
                  }
                  if(newitem.laiyuan){ // 来源
                    let imdata = parentobj.datadictList.laiyuan;
                    for(let i=0;i<imdata.length;i++){
                      if(newitem.laiyuan == imdata[i].value || newitem.laiyuan == imdata[i].name ){
                          formdata2.laiyuan = [imdata[i].value];
                      }
                    }
                  }
                  if(newitem.peijianleixing){ // 配件类型
                    let imdata = parentobj.datadictList.peijianleixing;
                    for(let i=0;i<imdata.length;i++){
                      if(newitem.peijianleixing == imdata[i].value || newitem.peijianleixing == imdata[i].name ){
                        formdata2.peijianleixing = [imdata[i].value];
                      }
                    }
                  }
                  if(newitem.daopeijianleixing){ // 到配件类型
                    let imdata = parentobj.datadictList.daopeijianleixing;
                    for(let i=0;i<imdata.length;i++){
                      if(newitem.daopeijianleixing == imdata[i].value || newitem.daopeijianleixing == imdata[i].name ){
                        formdata2.daopeijianleixing = [imdata[i].value];
                      }
                    }
                  }
                  if(newitem.bengongxuid){ // 本工序
                    let imdata = parentobj.datadictList.bengongxuid;
                    for(let i=0;i<imdata.length;i++){
                      if(newitem.bengongxuid == imdata[i].gongxudaima || newitem.bengongxuid == imdata[i].zhongwenmiaoshu || newitem.bengongxuid == imdata[i].id ){
                          formdata2.bengongxuid = {id: imdata[i].id, name: imdata[i].gongxudaima}
                          break;
                      }
                    }
                  }
                  if(newitem.daogongxuid){ // 到工序
                    let imdata = parentobj.datadictList.bengongxuid;
                    for(let i=0;i<imdata.length;i++){
                      if(newitem.daogongxuid == imdata[i].gongxudaima || newitem.daogongxuid == imdata[i].zhongwenmiaoshu || newitem.daogongxuid == imdata[i].id){
                          formdata2.daogongxuid = {id: imdata[i].id, name: imdata[i].gongxudaima}
                          break;
                      }
                    }
                  }
              }
              // 
              console.log("update:", formdata2)
              if(newitem.id){
                 await crudModuleUpdateApi(parentobj.value, newitem.id, formdata2, true)
              }
           }
           this.handlerPutFieldUpdatevision(); // bom版本更新

        },
        // 更新物料档案bom版本更新方法
        async handlerPutFieldUpdatevision(){
            console.log("this.oneboom", this.oneboom)
            let vnum = this.oneboom.bomm_ver + 1;
            putUpdateFieldApi('wuliaoxinxi', this.oneboom.id, {field_name: 'bomm_ver', value:  vnum}, true)
        },
        // 删除数据处理方法
        async handlerRemoveSaveForm(parentData, fdata){
          let delData = [];
          for(let i=0;i< fdata.length;i++){
            delData.push(fdata[i].id);
          }
          await crudModuleBatchDelApi(parentData.value, {ids: delData}, true);
        },
        // 数据比较(新数据和旧数据进行比较，返回新增、更新和删除的项数组)
        getArrayChanges(newArray, oldArray, idKey = 'id') {
          const changes = {
            added: [],
            updated: [],
            removed: []
          };
          // 检查新增和更新的项
          newArray.forEach(newItem => {
            const oldItem = oldArray.find(old => old[idKey] === newItem[idKey]);
            if (!oldItem) {
              changes.added.push(newItem);
            } else if (!_.isEqual(newItem, oldItem)) {
              changes.updated.push({ old: oldItem, new: newItem });
            }
          });
          // 检查删除的项
          oldArray.forEach(oldItem => {
            if (!newArray.find(newItem => newItem[idKey] === oldItem[idKey])) {
              changes.removed.push(oldItem);
            }
          });
          return changes;
        },
        //比较数组变化
        getChangedItems(newArray, oldArray, compareKeys) {
          return newArray.filter(newItem => {
            const oldItem = oldArray.find(old => old.id === newItem.id); // 假设每个对象有唯一id
            if (!oldItem) return true; // 新添加的项
            
            // 检查指定的键是否有变化
            return compareKeys.some(key => newItem[key] !== oldItem[key]);
          });
        },
        handlerRplace(val){
            if(val.includes("/")){
            let newStr = val.replace(/\//g, "");
            return newStr
            }else{
            return val;
            }
        },
        // 批核
        async piheData(){
          console.log(this.oneboom)
          for(let i=0; i< 3;i++){
            let formobj = {field_name:'', value: ''};
            if(i==0){// bom批核
              formobj.field_name = 'bomm_ap_flag'
              formobj.value = 1;
              await putUpdateFieldApi('wuliaoxinxi', this.oneboom.id, formobj, true)
            }else if(i==1){ // bom批核人
              if(this.oneboom.bomm_ap_user == this.userinfo.name){
                continue;
              }else{
              formobj.field_name = 'bomm_ap_user'
              formobj.value = this.userinfo.name;
              await putUpdateFieldApi('wuliaoxinxi', this.oneboom.id, formobj, true)
              }
            }else if(i==2){ // bom批核时间
              formobj.field_name = 'bomm_ap_date'
              formobj.value = this.handlerdateTime();
              let resdata = await putUpdateFieldApi('wuliaoxinxi', this.oneboom.id, formobj, true)
              if(resdata.status == 200){
                this.$message({type: 'success', message: "批核成功"});
                let listtime = setTimeout(()=>{
                  clearTimeout(listtime)
                  this.$emit('getList', 12)
                }, 200)
              }
            }
          }
         
        },
        // 反批核
        async fanpiheData(){
          let formobj = {}
          formobj.field_name = 'bomm_ap_flag'
          formobj.value = 0;
          let resdata = await putUpdateFieldApi('wuliaoxinxi', this.oneboom.id, formobj, true)
          if(resdata.status == 200){
            this.$message({type: 'success', message: "反批核成功"});
            let listtime = setTimeout(()=>{
              clearTimeout(listtime)
              this.$emit('getList', 13)
            }, 200)
          }
        },
        saveFn() {
            
            let saveid = this.parentData.wuliaobianmaid ? this.parentData.wuliaobianmaid : this.parentData.id;
            this.handlerWLQDSaveTabelFilter(saveid);
            return;
            
            // this.$refs['preForm'].getFormData()
            // .then((formData) => {
            //     this.formdatasubmit = formData;
            //     if (this.id > 0) { // 编辑
            //         this.upladData(this.id, formData)
                    
            //     } else {
            //         // 原代码
            //         this.formdatasubmit = formData;
            //         this.savaData(formData)
            //     }
            // })
            // .catch((error) => {
            //     this.$message.error(error)
            // })
        },
        // 实体列表新增保存
        savaData(data) {
            this.loading = true
            if (this.crud) {
              data.crud_id = this.crud.crud_id
              data.crud_value = this.crud.crud_value
            }
            // 原代码
            crudModuleSaveDataApi(this.keyName, data)
            .then((res) => {
                if (res.status == 200) {
                    this.handleClose()
                    let saveid = res.data.id;
                    this.isSubmit = 0;
                    this.$emit('getList')
                }
                this.loading = false
            })
            .catch((err) => {
                this.loading = false
            })
        },
        // 实体列表更新保存
        upladData(id, data) {
            this.loading = true
            if (this.crud) {
            data.crud_id = this.crud.crud_id
            data.crud_value = this.crud.crud_value
            }
            
            // 原代码
            crudModuleUpdateApi(this.keyName, id, data)
            .then((res) => {
                if (res.status == 200) {
                // this.handleClose()
                this.$emit('getList')
                this.isSubmit = 0;
                
                }
                this.loading = false
            })
            .catch((err) => {
                this.loading = false
            })
            
        },
  
        handleClose() {
            // this.$refs['preForm'].resetForm()
            this.drawer = false
            this.id = 0
            this.isSubmit = 0;
        },
        // dengshunbo 2025-1-14 时间戳转换
        hadnlerFilterReturn(time=''){
            let rtime = ''
            if(time){
            rtime = new Date(time).getTime();
            }else{
            rtime = new Date().getTime();
            }
            return rtime;
        },
        hadnlerriqiFilter(times) {
           if(times){
              if(times == '0000-00-00'){
                 return '';
              }else{
                 return times;
              }
           }else{
              return '';
           }
        },
        // 获取当前时间
        handlerdateTime(){
            let time = new Date();
            let year = time.getFullYear(); // 年
            let Mont = time.getMonth() + 1 > 9 ? time.getMonth() + 1 : '0' + (time.getMonth() + 1); // 月
            let date = time.getDate() > 9 ? time.getDate() : '0' + time.getDate(); // 日
            let hours = time.getHours() > 9 ? time.getHours() : '0' + time.getHours(); // 时
            let minutes = time.getMinutes() > 9 ? time.getMinutes() : '0' + time.getMinutes(); // 分
            return year + '-' + Mont + '-' + date + ' '+ hours + ':' + minutes;
        }

     
      
    }
  }
  </script>
  <style scoped lang="scss">
  /deep/.el-drawer__body {
    padding: 10px 20px 50px 20px;
  }
  .p10 {
    width: 100%;
    padding: 0 10px;
  }
  .fixnew{
    position: absolute;
    top:-42px;left:0;
  }
  /deep/ .el-tabs__header .el-tabs__item{
    line-height:40px!important;
  }
  /deep/ .el-upload--picture-card{
    width:100px;height:100px;line-height: 100px;
  }
  </style>
  